﻿using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows;
using NoMvvm.Demo.Models;
using NoMvvm.MEF;

namespace NoMvvm.Demo.ViewModels
{
    [ViewModel("Main")]
    public sealed class MainViewModel : ViewModel
    {
        private readonly Telescope _telescope;

        [ImportingConstructor]
        public MainViewModel(Telescope telescope)
        {
            _telescope = telescope;
        }

        public async void Refresh()
        {
            This.Planets = null;
            This.IsBusy = true;
            This.CanRefresh = false;

            try
            {
                This.Planets = (await _telescope.MeasurePlanets())
                    .Select(p =>
                        {
                            dynamic viewModel = new ViewModel();
                            viewModel.Name = p.Name;
                            viewModel.Diameter = p.Diameter + " KM";
                            viewModel.Info = (Action)delegate
                            {
                                //Note that calling MessageBox.Show() directly violates the MVVM pattern
                                //I am mainly using it just to demonstrate an in-line ViewModel
                                MessageBox.Show("Test!");
                            };
                            return viewModel;
                        });
            }
            finally
            {
                This.IsBusy = false;
                This.CanRefresh = true;
            }
        }
    }
}